home *** CD-ROM | disk | FTP | other *** search
Text File | 1994-06-26 | 1.7 KB | 96 lines | [TEXT/MPS ] |
- /*
- File: Synchronization.cp
-
- Contains: Some classes useful for synchronizing multiple threads or tasks.
- Simple semaphores and NuKernel-style EventGroups are implemented.
-
- Written by: Dave Falkenburg
-
- Copyright: © 1993 by Dave Falkenburg, all rights reserved.
-
- Change History (most recent first):
-
- */
-
- #include "Synchronization.h"
-
- /*
- TO DO: Get this working at interrupt level
- Add sanity checks?
- */
-
- TSimpleSemaphore::TSimpleSemaphore(void)
- {
- fCounter = 1;
- fOwner = kNoThreadID;
- fResultCode = noErr;
-
- // *** Don’t forget to initialize the waiting list ***
- }
-
- TSimpleSemaphore::~TSimpleSemaphore(void)
- {
- // Wake up everybody waiting for this semaphore
-
- ThreadBeginCritical();
- fSleepCount = 0;
- fOwner = kNoThreadID; // this indicates an error!
- ThreadEndCritical();
-
- // *** Don’t forget to wakeup the whole waiting list ***
- }
-
- OSErr
- TSimpleSemaphore::Up(void)
- {
- ThreadID thisThread;
- OSErr resultCode;
-
- GetCurrentThread(&thisThread);
- ThreadBeginCritical();
-
- fCounter++;
- if (fCounter == 0)
- {
- }
-
- ThreadEndCritical();
- }
-
- OSErr
- TSimpleSemaphore::Down(void)
- {
- ThreadID thisThread;
- OSErr resultCode;
-
- GetCurrentThread(&thisThread);
- ThreadBeginCritical();
-
- fCounter--;
- if (fCounter == 0)
- {
- // We got the semaphore (yea!)
-
- fOwner = thisThread;
- }
- else if (fCounter < 0)
- {
- // Someone else has the semaphore, wait for it…
- // Put us on the waiting list and go to sleep.
-
- SetThreadStateEndCritical(thisThread,kStoppedThreadState,fOwner);
- ThreadBeginCritical();
-
- // We’ve been awakened! Remember: this doesn’t mean we got
- // the lock, somebody may have destroyed the semaphore!
-
- if (fOwner != thisThread)
- resultCode = threadProtocolErr;
- }
-
- ThreadEndCritical();
-
- return resultCode;
- }
-
-